<script type="text/javascript">
var trCount = ${salesOrderInstance?.salesOrderDetails?.size()?:0}
	trCount -=1
function addOrderDetail(){
	if($("#searchProductId").val() == ''){
		return false;
	}
    $.blockUI();
    $.ajax({
        url: "${createLink(controller:'salesOrderAjax', action: 'productProperty220')}",
        data: { serialNumber: $("#searchProductNumber").val() },
        dataType: "json",
        type: "POST",
        success: productPropertyCallback
    });
}
function productPropertyCallback(data){
    $.unblockUI();
	trCount ++
	var rowid = trCount + 1
	if(rowid > 99){
		alert("max row is 100");
		return false;
	}
	var css = (trCount % 2 == 0)?"odd":"even";
	var hasBomDetail = data.hasBom
	var price = hasBomDetail?data.price :$("#searchProductPrice").html()
	var discount = hasBomDetail?1 : data.discount
	var serialNumber = (rowid < 10) ? '0' + rowid : '' + rowid
	var deliveryCycle = data.delivery

	var rowspan = hasBomDetail?("rowspan='"+($(data.bomDetails).length + 1)+"'"):""
	$("#salesOrderDetailList").append(
		$("<tr class='prop "+css+"' childs='"+serialNumber+"' ></tr>").append(
			$("<td "+rowspan+" name='serialNumber'><span>"+serialNumber+"</span></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].serialNumber" value="'+serialNumber+'" type="hidden" />')
			).append(
				$("<br/>")
			).append(
				$('<a href="#addSalesOrderDetailLink" delete="delete">${message(code: 'default.button.delete', default: 'Delete')}</a>').bind('click', myDeleteRow)
			)
		).append(
			$("<td name='openDetail'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].openDetail" type="checkbox" onclick="return false;"/>').attr("checked", hasBomDetail)
            )
		).append(
			$("<td name='product.id'></td>").append(
				$('<span>'+$("#searchProductNumber").val()+'</span>')
			).append(
				$('<input name="salesOrderDetails['+trCount+'].product.id" value="'+$("#searchProductId").val()+'" type="hidden" />')					
			)
		).append(
			$("<td name='product.name'></td>").append(
				$('<span>'+$("#searchProductName").html()+'</span>')
			)
		).append(
			$("<td name='product.standard'></td>").append(
				$('<span>'+$("#searchProductStandard").html()+'</span>')
			)
		).append(
			$("<td name='category'></td>").append(
				$('<span>'+(data.category?data.category:'')+'</span>')
			)
		).append(
			$("<td name='price' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].price" value="'+$.formatNumber(price, "###,##0.000000")+'" readonly="readonly" />')
			).append(
                $('<span>('+data.allowZeroPrice+')</span>')
            )
		).append(
			$("<td name='discount' class='value number'></td>").append(
				$('<input name="salesOrderDetails['+trCount+'].discount" value="'+discount.toFixed(4) +'"  readonly="readonly" style="width:55px;" />')					
			)
		).append(
			$("<td name='quantity' class='value number'></td>").append(
				$("<input name='salesOrderDetails["+trCount+"].quantity' value='0' type='text' >").keypress(myKeypress).focus(myFocus).blur(myBlur).bind('paste', myPaste).change(myChange)
			)
		).append(
			$("<td name='deliveryLimitation'></td>").append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation" value="date.struct" />'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_year" value=""/>'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_month" value=""/>'
			).append(
				'<input type="hidden" name="salesOrderDetails['+trCount+'].deliveryLimitation_day" value=""/>'
			).append(
				$("<input target='salesOrderDetails["+trCount+"].deliveryLimitation' datepicker='datepicker' type='text' style='width:80px;'>").datepicker({
					  dateFormat: 'yy-mm-dd'
					, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
					, onClose: function(dateText, inst) {
						$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
						$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
						$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
					}
				}).attr("readonly", true)
			).append(
				$("<span>"+deliveryCycle+"</span>")
			)
		).append(
			$("<td name='amount' class='value number'></td>").append(
                $("<span>0.00</span>")
            ).append(
                $('<input name="salesOrderDetails['+trCount+'].amount" value="0.00" type="hidden" />')
            )
		)
	)

	var j = -1
	$(data.bomDetails).each(function(){
		j++
		var sumSerialNumber = (j+1 < 10)? '0' + (j+1) : ''+(j+1)
		$("#salesOrderDetailList").append(
			$("<tr class='prop "+css+"' parent='"+serialNumber+"'></tr>").append(
				$("<td name='serialNumber'>(+)<span>"+sumSerialNumber+"</span></td>").append(
					$('<input name="salesOrderDetails['+trCount+'].salesOrderDetailDetails['+j+'].serialNumber" value="'+sumSerialNumber+'" type="hidden" />')
				)
			).append(
				$("<td name='product.id'></td>").append(
					$('<span>'+this.serialNumber+'</span>')
				).append(
					$('<input name="salesOrderDetails['+trCount+'].salesOrderDetailDetails['+j+'].product.id" value="'+this.id+'" type="hidden" />')					
				)
			).append(
				$("<td name='product.name'></td>").append(
					$('<span>'+this.name+'</span>')
				)
			).append(
				$("<td name='product.standard'></td>").append(
					$('<span>'+this.standard+'</span>')
				)
			).append(
				$("<td name='category'></td>").append(
					$('<span>'+(this.category?this.category:'')+'</span>')
				)
			).append(
				$("<td name='price' class='value number'></td>").append(
					$('<input name="salesOrderDetails['+trCount+'].salesOrderDetailDetails['+j+'].price" value="'+$.formatNumber(this.price, "###,##0.000000")+'" readonly="readonly" />')					
				).append(
                    $('<span>('+this.isAllowZeroPrice+')</span>')
                )
			).append(
				$("<td name='discount' class='value number'></td>").append(
					$('<input name="salesOrderDetails['+trCount+'].salesOrderDetailDetails['+j+'].discount" value="'+(this.discount).toFixed(4)+'"  readonly="readonly" style="width:55px;"/>')					
				)
			).append(
				$('<td name="quantity" class="value number"></td>').append(
					$('<input name="salesOrderDetails['+trCount+'].salesOrderDetailDetails['+j+'].quantity" value="0" type="text" readonly="readonly" />')
				).append(
					$('<span>' + this.dosage + '</span>')
				).append(
					$('<span>,</span>')
				).append(
					$('<span>' + this.quota + '</span>')
				)
			).append(
				$("<td></td>")
			).append(
				$("<td name='amount' class='value number'></td>").append(
                    $("<span>0.00</span>")
                ).append(
                    $('<input name="salesOrderDetails['+trCount+'].salesOrderDetailDetails['+j+'].amount" value="0.00" type="hidden" />')
                )
			)
		)
	});
    //重置搜索框
    initSearchProduct();
    $("#searchProductNumber").focus();
}
function myBlur(){
	var v = parseInt($.formatNumber(this.value, "##0.00"), 10);
        v = isNaN(v) ? $(this).data("before") : v;
	//set value
	this.value = $.formatNumber(v, "###,##0.00")
		
	//get value--parent quantity
	var parent_quantity = v

	//get parent tr
	var parent_tr = $(this).parent().parent();
	
	//get parent price
	var parent_price = parent_tr.children("td[name=price]").children(":first-child").val()
        parent_price = $.formatNumber(parent_price, "#0.000000")
        parent_price = parseFloat(parent_price, 10)
	
	//get parent disocunt
	var parent_discount = parent_tr.children("td[name=discount]").children(":first-child").val()
        parent_discount = $.formatNumber(parent_discount, "#0.0000")
        parent_discount = parseFloat(parent_discount, 10)

	//parent amount
	var parent_amount_td = parent_tr.children("td[name=amount]")
	//get old row amount
	var old_row_amount = parent_amount_td.children(":first-child").html()
		old_row_amount = $.formatNumber(old_row_amount, "##0.00")
        old_row_amount = parseFloat(old_row_amount, 10)
	//calculate new row amount
	var new_row_amount = parent_price.mul(parent_discount).mul(parent_quantity)
	//set row amount
	parent_amount_td.children(":first-child").html($.formatNumber(new_row_amount, "###,##0.00"))
    parent_amount_td.children(":nth-child(2)").val($.formatNumber(new_row_amount, "###,##0.00"))


	//total amount
	var total_amount_td = $("td[name=totalAmount]")
    //get total amount
	var old_total_amount = total_amount_td.html()
		old_total_amount = $.formatNumber(old_total_amount, "##0.00")
        old_total_amount = parseFloat(old_total_amount, 10)
    //calculate new total amount
	var new_total_amount = old_total_amount.sub(old_row_amount).add(new_row_amount)

    //set total amount
	total_amount_td.html($.formatNumber(new_total_amount, "###,##0.00"))

	//get childs tr parent property
	var childs_tr_parent = parent_tr.attr("childs")
	
	$("tr[parent="+childs_tr_parent+"]").each(function(){
	    //get child price
		var child_price = $(this).children("td[name=price]").children(":first-child").val()
			child_price = $.formatNumber(child_price, "#0.000000")
            child_price = parseFloat(child_price, 10)
		//get child discount
		var child_discount = $(this).children("td[name=discount]").children(":first-child").val()
            child_discount = parseFloat(child_discount, 10)
		//get quantity td
        var child_quantity_td = $(this).children("td[name=quantity]")
			
		//get dosage
		var dosage = $(child_quantity_td).children(":nth-child(2)").html()
			dosage = dosage.replace(/\n/g, "")
            dosage = parseFloat(dosage, 10)

		var quota = $(child_quantity_td).children(":nth-child(4)").html()
			quota = quota.replace(/\n/g, "")
            quota = parseFloat(quota, 10)
        //debugger;
				
		//set quantity
		$(child_quantity_td).children(":first-child").val($.formatNumber(parent_quantity.mul(dosage.div(quota)), "###,##0.000"))
		//set amount
        var child_amount = $.formatNumber( parent_quantity.mul(dosage.div(quota)).mul(child_price).mul(child_discount), "###,##0.00")
		$(this).children("td[name=amount]").children(":first-child").html(child_amount)
        $(this).children("td[name=amount]").children(":nth-child(2)").val(child_amount)
	})
}
function myDeleteRow(){
    if($(this).parent().parent().parent().attr("id") != 'salesOrderDetailList'){
        return false;
    }
	if(!confirm('Delete!')){
		return false;
	}
	//get parent tr
	var parent_tr = $(this).parent().parent();
	//get childs tr parent property
	var childs_tr_parent = parent_tr.attr("childs")
	
	$("tr[parent="+childs_tr_parent+"]").each(function(){
		$(this).remove();
	})
	
	//get row amount
	var amount = $(parent_tr).children("td[name=amount]").html().trim()
		amount = $.formatNumber(amount, "#0.00")

	var total_amount_td = $("td[name=totalAmount]")
		
	//get total amount
	var old_total_amount = total_amount_td.html()
		old_total_amount = $.formatNumber(old_total_amount, "##0.00")
	//calculate new total amount
	var new_total_amount = old_total_amount.sub(amount)

	//set total amount
	total_amount_td.html($.formatNumber(new_total_amount, "###,##0.00"))
	
	$(parent_tr).remove()

	refreshSerialNumber();
}

function refreshSerialNumber(){
	var rowindex = -1
	//get table all parent row
	$("#salesOrderDetailList > tr[childs]").each(function(){
		rowindex ++;
		var new_serialNumber = (rowindex + 1 < 10)? "0" + (rowindex + 1) : "" + (rowindex + 1);
		var old_serialNumber = $(this).attr("childs")
		//update tr childs
		$(this).attr("childs", new_serialNumber).children("td").each(function(){
			switch($(this).attr('name')){
				case 'serialNumber':
					$(this).children(":nth-child(1)").html(new_serialNumber);
					$(this).children(":nth-child(2)").val(new_serialNumber);
				case 'openDetail':
				case 'product.id':
				case 'price':
				case 'discount':
				case 'quantity':
				case 'deliveryLimitation':
				case 'description':
					$(this).children("input").each(function(){
						var old_name=$(this).attr("name")||$(this).attr("target");
						var begin = old_name.indexOf("[", 0);
						var end = old_name.indexOf("]", begin);
						var new_name = old_name.substring(0, begin + 1) + rowindex + old_name.substr(end);
						//$(this).attr("name", new_name).attr("id", new_name);
						if($(this).attr("name")){$(this).attr("name", new_name)}
						if($(this).attr("id")){$(this).attr("id", new_name)}
						if($(this).attr("target")){
							var deliveryCycle = $(this).parent().children(":last-child").html().replace(/\r\n/g, "").trim();
							
							$(this).attr("target", new_name).datepicker("destroy").datepicker({
								dateFormat: 'yy-mm-dd'
								, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
								, onClose: function(dateText, inst) {
									$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
									$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
									$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
								}
							})
						}
					})
					break;
			}

		})
		$("tr[parent="+old_serialNumber+"]").attr("parent", new_serialNumber).children("td").each(function(){
			switch($(this).attr('name')){
				case 'serialNumber':
				case 'product.id':
				case 'price':
				case 'discount':
				case 'quantity':
					$(this).children("input").each(function(){
						var old_name=$(this).attr("name");
						var begin = old_name.indexOf("[", 0);
						var end = old_name.indexOf("]", begin);
						var new_name = old_name.substring(0, begin + 1) + rowindex + old_name.substr(end);
						$(this).attr("name", new_name).attr("id", new_name);
					})
					break;
			}
		})
	})

    
}

</script>
